﻿using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using ServBus.ListForm2010.Controls;
using ServBus.ListForm2010.License;
using ServBus.ListForm2010.Resources;

namespace ServBus.ListForm2010.AdministrationPages
{
    public partial class WebAppActivate : System.Web.UI.Page
    {
        #region Controls
        protected BreadCrumbNav bcNav;
        protected Repeater rptWebApps;
        protected Label lblError;
        #endregion

        private static readonly Guid WSP_ID = new Guid("CCFBCF55-669A-4992-A905-044A2A4B3039");
        private static DllResource Resource = new DllResource("ServBus.ListForm2010.Common.Resources|AdminPages");

        protected void Page_Load(object sender, EventArgs e)
        {
            bcNav.AddLink(Resource.GetString("WebApp_Activation_Nav"), null, null);
        }

        private DataTable BuildWebAppTable()
        {
            DataTable result = new DataTable();
            result.Columns.Add("WebApp", typeof(string));
            result.Columns.Add("WebAppId", typeof(string));
            result.Columns.Add("ButtonText", typeof(string));
            result.Columns.Add("StatusUI", typeof(string));
            result.Columns.Add("ConfirmJs", typeof(string));

            // Find WebApps
            foreach (SPWebApplication webapp in SPWebService.ContentService.WebApplications)
            {
                if (webapp.IsAdministrationWebApplication)
                    continue;
                if (webapp.IisSettings.Count <= 0)
                    continue;
                DataRow row = result.NewRow();
                row["WebApp"] = webapp.Name;
                row["WebAppId"] = webapp.Id.ToString();
                if (Activations.IsActivatedOnWebApp(webapp))
                {
                    row["ButtonText"] = SPResource.GetString("FeatureDeactivate", new object[0]);
                    row["StatusUI"] = SPResource.GetString("FeatureActive", new object[0]);
                    row["ConfirmJs"] = string.Format("if(!confirm('{0}')) return false;",
                        Resource.GetString("Deactivate_Warning"));
                }
                else
                {
                    row["ButtonText"] = SPResource.GetString("FeatureActivate", new object[0]);
                    row["StatusUI"] = string.Empty;
                    row["ConfirmJs"] = "";
                }
                result.Rows.Add(row);
            }

            return result;
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            string errorMsg;
            if (!(new Activations(SPFarm.Local)).IsLicenseValid(out errorMsg))
            {
                this.lblError.Text = errorMsg;
            }
            else
            {
                DataTable webApps = BuildWebAppTable();
                this.rptWebApps.DataSource = webApps;
                this.rptWebApps.DataBind();

                if (webApps.Rows.Count == 0)
                {
                    this.lblError.Text = Resource.GetString("No_Activated_WebApp");
                }
            }
        }

        protected void btnAction_Click(object sender, CommandEventArgs e)
        {
            SPWebApplication webapp = SPWebService.ContentService.WebApplications[new Guid(e.CommandArgument.ToString())];
            SPSolution solution = SPFarm.Local.Solutions[WSP_ID];
            if (Activations.IsActivatedOnWebApp(webapp))
            {
                Activations.DeactivateWebApp(webapp);
                RetractSolution(solution, webapp);
            }
            else
            {
                DeploySolution(solution, webapp);
                Activations.ActivateWebApp(webapp);
            }
        }

        private bool IsLocalDeploy()
        {
            return ((SPServer.LocalServerRole == SPServerRole.SingleServer) ||
                (SPFarm.Local.TimerService.Instances.Count == 1));
        }

        private void DeploySolution(SPSolution solution, SPWebApplication webapp)
        {
            Collection<SPWebApplication> webapps = new Collection<SPWebApplication>();
            webapps.Add(webapp);
            if (IsLocalDeploy())
            {
                solution.DeployLocal(true, webapps, true);
            }
            else
            {
                solution.Deploy(DateTime.Now, true, webapps, true);
            }
        }

        private void RetractSolution(SPSolution solution, SPWebApplication webapp)
        {
            Collection<SPWebApplication> webapps = new Collection<SPWebApplication>();
            webapps.Add(webapp);
            if (IsLocalDeploy())
            {
                solution.RetractLocal(webapps);
            }
            else
            {
                solution.Retract(DateTime.Now, webapps);
            }
        }
    }
}
